<template>
    <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <!-- 添加按钮区域 -->
        <el-row :gutter="20">
            <el-col :span="7">
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>
        <!-- 角色列表区域 -->
        <el-table
        :data="rolesList"
        border
        stripe
        style="width: 100%">
        <!-- 展开行 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row  v-for="(item, index) in scope.row.children" :key="item.id" :class="['bdBottom', index === 0 ? 'bdTop' : '','vcenter']">
                <!-- 一级权限 -->
                <el-col :span="5">
                  <el-tag type="primary" closable @close="removeRightById(scope.row, item.id)">{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级权限和三级权限 -->
                <el-col :span="19">
                  <el-row v-for="(item2, index2) in item.children" :key="item2.id" :class="[index2 == item.children.length-1?'':'bdBottom','vcenter']">
                    <el-col :span="6">
                      <el-tag closable type="success" @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" prop="roleName">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)" size="mini">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)" size="mini">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 添加角色弹出框区域 -->
        <el-dialog
          title="添加角色"
          :visible.sync="addDialogVisible"
          width="30%"
          @close="resetDialog">
          <!-- 内容主体 -->
          <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole">添 加</el-button>
          </span>
        </el-dialog>
        <!-- 修改角色弹出框区域 -->
        <el-dialog
          title="修改角色"
          :visible.sync="editDialogVisible"
          width="30%"
          @close="resetEditDialog">
          <!-- 内容主体 -->
          <el-form ref="editFormRef" :model="editRole" label-width="80px" :rules="editFormRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editRole.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="editRole.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRoles">修 改</el-button>
          </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog
          title="提示"
          :visible.sync="setRightDialogVisible"
          width="50%"
          @close="setRightDialogClose">
          <!-- 树形控件 -->
          <el-tree
            :data="rightsList"
            show-checkbox
            node-key="id"
            :default-checked-keys="defKeys"
            :props="defaultProps"
            default-expand-all
            ref="treeRef">
          </el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
    // 角色列表数据
      rolesList: [],
      // 添加角色弹出框显示
      addDialogVisible: false,
      // 添加角色对话框表单绑定数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色对话框表单规则验证
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '角色名称长度在2-8位', trigger: 'blur' }
        ],
        roleDesc: [
          { min: 2, max: 10, message: '角色名称长度在2-10位', trigger: 'blur' }
        ]
      },
      // 修改角色绑定数据
      editRole: {},
      // 修改角色对话框显示控制
      editDialogVisible: false,
      // 修改角色对话框表单规则验证
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '角色名称长度在2-8位', trigger: 'blur' }
        ],
        roleDesc: [
          { min: 2, max: 10, message: '角色名称长度在2-10位', trigger: 'blur' }
        ]
      },
      // 展示分配权限对话框
      setRightDialogVisible: false,
      // 所有权限数据
      rightsList: [],
      // 树形控件配置
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认选中节点值
      defKeys: [],
      // 要修改权限的角色id
      roleId: 0
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.$message.success('获取角色列表成功')
      this.rolesList = res.data
    },
    // 重置添加角色对话框表单
    resetDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 发生请求添加角色
    addRole () {
      this.$refs.addFormRef.validate(async (valid, error) => {
        if (!valid) return this.$message.error('请按格式输入指定内容')
        const { data: res } = await this.$http.post('/roles', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    // 监听修改角色按钮
    async showEditDialog (id) {
      console.log(id)
      const { data: res } = await this.$http.get('/roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.editRole = res.data
      this.editDialogVisible = true
    },
    // 重置修改角色对话框表单
    resetEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 发生请求修改角色
    editRoles () {
      this.$refs.editFormRef.validate(async (valid, error) => {
        if (!valid) return this.$message.error('请正确填写角色信息')
        const { data: res } = await this.$http.put('/roles/' + this.editRole.roleId, {
          roleName: this.editRole.roleName,
          roleDesc: this.editRole.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('更新角色信息失败')
        this.$message.success('更新用户信息成功')
        this.getRolesList()
        this.editDialogVisible = false
      })
    },
    // 删除角色
    async deleteRole (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((error) => error)
      if (confirmRes === 'confirm') {
        const { data: rest } = await this.$http.delete('/roles/' + id)
        if (rest.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功')
        this.getRolesList()
      } else {
        return this.$message.info('已取消删除')
      }
    },
    // 监听删除权限事件
    async removeRightById (role, rightID) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmRes === 'confirm') {
        const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${rightID}`)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        // 服务器返回的数据中res.data即为最新的权限信息，防止页面刷新，提高用户体验，不使用this.getRolesList()
        role.children = res.data
        this.$message.success('删除权限成功')
      } else {
        this.$message.info('已取消删除')
      }
    },
    // 分配权限对话框展示
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 获取权限数据
      const { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      // 把获取到的权限数据保存到rightsList中
      this.rightsList = res.data
      // 获取三级权限id
      this.getLeafKeys(role, this.defKeys = [])
      this.setRightDialogVisible = true
    },
    // 通过递归的方法获取三级权限ID，并保存到defKeys中
    getLeafKeys (node, arr) {
      // 当前节点不包含children属性，说明为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框关闭,解决调用getLeafKeys时defKeys不为空导致的bug
    setRightDialogClose () {
      this.defKeys = []
    },
    // 发生请求修改权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`/roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) return this.$message.error('修改权限失败')
      this.getRolesList()
      this.$message.success('修改权限成功')
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.bdTop {
  border-top: 1px solid #eee;
}
.vcenter {
  display:flex;
  align-items: center;
}
</style>
